package hotLeetcode;

import java.util.HashMap;
import java.util.Map;

public class H138Leetcode {

    class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }

    public Node copyRandomList(Node head) {
        Node newNode = new Node(-1);
        Node dummy = new Node(-1);
        dummy.next = head;
        dummy = dummy.next;
        Map<Integer, Node> map = new HashMap<>();
        int i = 0;

        while (dummy != null) {
            Node random = dummy.random;
            map.put(i++, random);
            dummy = dummy.next;
        }
        int index = 0;
        while (head != null) {
            Node next = new Node(head.val);
            next.random = map.get(index++);
            newNode.next = next;
            head = head.next;
        }

        return newNode.next;
    }
    public Node copyRandomList2(Node head) {
        Map<Node, Node> map = new HashMap<>();
        Node cur = head;
        while (cur != null) {
            //不用根据索引，比较麻烦。 可以根据 原 --->  新 这样来存储
            map.put(cur, new Node(cur.val));
            cur = cur.next;
        }

        cur = head;
        while (cur != null) {
            map.get(cur).next = map.get(cur.next);
            map.get(cur).random = map.get(cur.random);
            cur = cur.next;

        }
        return map.get(head);
    }


}
